﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;

namespace LicPdaService
{
    public class PDAXmlPickUpdeProcess
    {
        /// <summary>
        /// 4.1拣货确认
        /// DataSource:Orders OrderDetail Pickdetail
        /// </summary>
        public static string GetPickUpde(XmlDocument doc)
        {
            #region 通用变量定义
            string userid = string.Empty;
            string whseid = string.Empty;
            string orderkey = string.Empty;
            string master_label = string.Empty;
            string sku = string.Empty;
            string udf1 = string.Empty;
            string batch = string.Empty;
            double label_qty = 0;
            string return_status = "OK";
            string strSql = string.Empty;
            List<string> sqllists = new List<string>();

            XmlDocument docreturn = new XmlDocument();//返回报文
            XmlDeclaration dec = docreturn.CreateXmlDeclaration("1.0", "utf-8", null);//建立Xml的定义声明  
            docreturn.AppendChild(dec);
            XmlElement rootResult = docreturn.CreateElement("NewDataSet"); //创建根节点
            #endregion

            try
            {
                #region 参数源/数据更新
                App.DBconSet();
                string xml = doc.InnerXml;
                DataTable ldt = LicPdaService.App.Xml2DataTable(xml);
                try
                {
                    userid = ldt.Rows[0]["userid"].ToString();
                    whseid = ldt.Rows[0]["whseid"].ToString();
                    orderkey = ldt.Rows[0]["orderkey"].ToString();
                    if (whseid == "wh1" || whseid == "wh2")
                    {
                        DataTable ldt_dy = LicPdaService.App.GetPickDataTable();
                        for (int i = 0; i < ldt.Rows.Count; i++)
                        {
                            #region  获取参数
                            DataRow ldr = ldt_dy.NewRow();
                            string[] ls = ldt.Rows[i]["master_label"].ToString().Split('|');
                            if (ls.Length > 2)
                            {
                                sku = ls[0].ToString();
                                udf1 = ls[1].ToString();
                                batch = ls[2].ToString();
                                label_qty = double.Parse(ls[3].ToString());

                                ldr["userid"] = userid;
                                ldr["whseid"] = whseid;
                                ldr["orderkey"] = orderkey;
                                ldr["sku"] = sku;
                                ldr["udf1"] = udf1;
                                ldr["batch"] = batch;
                                ldr["qty"] = label_qty;

                            }
                            #endregion

                            #region 更新明细表/拣货表/库存表
                            strSql = @"SELECT TOP 1 P.whseid,P.pickdetailkey,P.orderkey,P.line_no,P.lot,P.inv_guid,P.sku,L.udf1,L.lottable01,P.qty,P.lottable10,P.status
                                FROM PickDetail AS P
                                LEFT JOIN Inventory AS I on P.lot = I.lot AND I.qty > 0
                                LEFT JOIN LotAttribute AS L ON P.lot = L.lot ";
                            strSql += " WHERE P.sku='" + sku + "' AND L.udf1='" + udf1 + "' AND L.lottable01='" + batch + "' AND P.qty=" + label_qty + " AND P.whseid='" + whseid + "' AND P.orderkey='" + orderkey + "' AND  P.status='12' AND P.line_no is not null AND P.line_no<>'' AND P.lot is not null AND P.lot<>''";
                            DataTable dt = App.GetDataTable(App.DBconWMS, strSql, "Inventory");

                            if (dt.Rows.Count > 0)
                            {
                                #region 更新明细表
                                ldr["pickdetailkey"] = dt.Rows[0]["pickdetailkey"].ToString();
                                ldr["inv_guid"] = dt.Rows[0]["inv_guid"].ToString();
                                ldr["line_no"] = dt.Rows[0]["line_no"].ToString();

                                string pickdetailkey = dt.Rows[0]["pickdetailkey"].ToString();
                                string inv_guid = dt.Rows[0]["inv_guid"].ToString();
                                string line_no = dt.Rows[0]["line_no"].ToString();

                                string dtlStatus = App.getStatus(whseid, orderkey, dt.Rows[0]["line_no"].ToString()); //明细当状态
                                string status = App.getMainStatus(whseid, orderkey); //主档状态
                                double pre_qty = double.Parse(App.getPre_qty(whseid, orderkey, line_no)); //明细预报量
                                double pick_qty = double.Parse(App.getPick_qty(whseid, orderkey, line_no)); //明细已拣货量
                                if (dtlStatus == "05" || dtlStatus == "06" || dtlStatus == "021")
                                {
                                    if (label_qty + pick_qty >= pre_qty)
                                    {
                                        status = "07";//已全部拣货
                                    }
                                    else
                                    {
                                        status = "06"; //拣货中
                                    }
                                }
                                else if (dtlStatus == "09")
                                {
                                    status = "09";
                                }

                                sqllists.Clear();

                                //更新PickDetail状态
                                strSql = "update pickdetail set status='03' where whseid='" + whseid + "' and pickdetailkey='" + pickdetailkey + "'";
                                sqllists.Add(strSql);

                                //更新Orderdetail状态
                                strSql = "update orderdetail set picked_qty=picked_qty+" + label_qty + ",allocated_qty=allocated_qty-" + label_qty + ", status='" + status + "'";
                                strSql += " where whseid='" + whseid + "' and orderkey='" + orderkey + "' and line_no='" + line_no + "'";
                                sqllists.Add(strSql);

                                //明细历史记录
                                int hisCount = App.getDtlHistory(whseid, orderkey, status, line_no);
                                if (hisCount == 0)
                                {
                                    strSql = "insert into OrdHistoryDtl(whseid,orderkey,line_no,status,operation,addwho,adddate) values ";
                                    strSql += "('" + whseid + "','" + orderkey + "','" + line_no + "','" + status + "','拣货确认','" + userid + "','" + DateTime.Now + "')";
                                    sqllists.Add(strSql);
                                }

                                //更新库存
                                strSql = "update inventory set allocated_qty=allocated_qty-(" + label_qty + ") ,picked_qty=picked_qty+(" + label_qty + ") where guid='" + inv_guid + "'";
                                sqllists.Add(strSql);

                                #endregion

                                if (!App.ExecuteSQLScriptLists(sqllists, App.DBconWMS))
                                {
                                    #region 错误日志写出
                                    return_status = return_status + "MasterLabel标签:" + ldt.Rows[i]["master_label"].ToString() + " 对应的拣货pickdetailkey：" + dt.Rows[0]["pickdetailkey"].ToString() + "执行拣货确认--明细表更新失败，请前往PC端重新执行拣货确认！！！".Replace("OK", "");
                                    App.Log("4.1 拣货确认-PDAXmlPickIntoryProcess.cs-2.x", return_status);
                                    #endregion
                                }
                                else
                                {
                                    #region 更新表头
                                    sqllists.Clear();
                                    string Mainstatus = "07"; //默认已全部拣货完成

                                    if (Mainstatus == "09")  //发货中
                                    {
                                        Mainstatus = "09";
                                    }
                                    else
                                    {
                                        if (App.getOrdeStatus(whseid, orderkey)) //存在status<='06'的明细状态
                                        {
                                            Mainstatus = "06";
                                        }

                                    }
                                    if (App.getPordStatus(whseid, orderkey)) //存在明细状态>='06' 时才更新表头
                                    {
                                        //更新出货表头
                                        strSql = "update orders set status='" + Mainstatus + "' where whseid='" + whseid + "' and orderkey='" + orderkey + "'";
                                        sqllists.Add(strSql);

                                        //插入出货表头历史表
                                        strSql = "insert into ordhistory(whseid,orderkey,status,operation,addwho,adddate) values ";
                                        strSql += "('" + whseid + "','" + orderkey + "','" + Mainstatus + "','拣货确认','" + userid + "','" + DateTime.Now + "')";
                                        sqllists.Add(strSql);

                                        if (!App.ExecuteSQLScriptLists(sqllists, App.DBconWMS))
                                        {
                                            #region
                                            return_status = return_status + "出货单:" + orderkey + " 表头状态更新失败，请前往PC端重新执行拣货确认！！！".Replace("OK", "");
                                            App.Log("4.1 拣货确认-PDAXmlPickIntoryProcess.cs-2.y", return_status);
                                            #endregion
                                        }
                                    }

                                    #endregion
                                }
                            }
                            #endregion
                        }
                    }
                    else
                    {
                        return_status = return_status + "拣货确认失败！！！  原因：PDA登录的厂别 "+whseid+" 不是有效厂别，可退出账号重新登录确认！".Replace("OK", "");
                    }
                }
                catch (Exception ex)
                {
                    App.Log("4.1 拣货确认-PDAXmlPickIntoryProcess.cs-2.1", ex.Message.ToString());
                }

                #endregion

                #region 构建XML报文
                XmlNode sku_result = docreturn.CreateElement("pickorder_return");

                XmlElement useridResult = docreturn.CreateElement("userid");
                useridResult.InnerText = userid;
                sku_result.AppendChild(useridResult);

                XmlElement whseidResult = docreturn.CreateElement("whseid");
                whseidResult.InnerText = whseid;
                sku_result.AppendChild(whseidResult);

                XmlElement orderkeyResult = docreturn.CreateElement("orderkey");
                orderkeyResult.InnerText = orderkey;
                sku_result.AppendChild(orderkeyResult);

                XmlElement return_statusResult = docreturn.CreateElement("return_status");
                return_statusResult.InnerText = return_status;
                sku_result.AppendChild(return_statusResult);

                rootResult.AppendChild(sku_result);
                #endregion
            }
            catch (Exception ex)
            {
                App.Log("4.1 拣货确认-PDAXmlPickIntoryProcess.cs-2.2", ex.Message.ToString());
            }
            docreturn.AppendChild(rootResult);
            return docreturn.InnerXml;
        }
    }
}
